/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser Public License for more details.

You should have received a copy of the GNU Lesser Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Source code : http://code.google.com/p/js-wow-api/
*/
Array.prototype.sum = function() { for(var i=0, sum=0; i < this.length; sum += Number(this[i++])); return sum; }
if ("Storage" in window) {
  Storage.prototype.setObject = function(key, value) { return this.setItem(key, JSON.stringify(value)); };
  Storage.prototype.getObject = function(key) { return this.getItem(key) && JSON.parse(this.getItem(key)); };
}

/*
us.battle.net
        en_US
        es_MX
us.media.blizzard.com
http://us.media.blizzard.com/wow/renders/items/item60210.jpg
http://us.media.blizzard.com/wow/icons/56/inv_weapon_rifle_39.jpg

eu.battle.net
        en_GB
        es_ES
        fr_FR
        ru_RU
        de_DE
http://eu.media.blizzard.com/wow/renders/items/item60210.jpg
http://eu.media.blizzard.com/wow/icons/56/inv_weapon_rifle_39.jpg

kr.battle.net
        ko_KR
http://kr.media.blizzard.com/wow/renders/items/item60210.jpg
http://kr.media.blizzard.com/wow/icons/56/inv_weapon_rifle_39.jpg


tw.battle.net
        zh_TW
http://tw.media.blizzard.com/wow/renders/items/item60210.jpg
http://tw.media.blizzard.com/wow/icons/56/inv_weapon_rifle_39.jpg

www.battlenet.com.cn
        zh_CN
http://content.battlenet.com.cn/wow/renders/items/item60210.jpg
http://content.battlenet.com.cn/wow/icons/56/inv_weapon_rifle_39.jpg
*/

/*
character media
eu
http://eu.battle.net/static-render/eu/suramar/149/51034261-profilemain.jpg
//http://eu.battle.net/static-render/eu/suramar/149/51034261-card.jpg
http://eu.battle.net/static-render/eu/suramar/149/51034261-inset.jpg
http://eu.battle.net/static-render/eu/suramar/149/51034261-avatar.jpg
*/

var region = 'eu'; // selected by default

var Front = {
  maxGem : 4,
  statics:{media:{icon:'http://#{domaine}/wow/icons/#{size}/#{icon}.jpg',
                  iconSize:[18,56],
                  render:'http://#{domaine}/wow/renders/items/item#{item}.jpg',
                  avatar:'http://#{domaine}/static-render/#{region}/#{avatar}'
                 },
           character:{api:'http://#{domaine}/api/wow/character/#{realm}/#{character}?locale=#{locale}&jsonp=#{jsonp}&fields=items,progression,professions,titles',//=guild,stats,talents,items,reputation,titles,professions,appearance,companions,mounts,pets,achievements,progression,pvp,quests
                      link:'http://#{domaine}/wow/#{locale}/character/#{realm}/#{character}/advanced'},
           item:{api:'http://#{domaine}/api/wow/item/#{item}?locale=#{locale}&jsonp=#{jsonp}',
                 link:'http://#{domaine}/wow/#{locale}/item/#{item}'},
           gem:{api:'http://#{domaine}/api/wow/item/#{item}?locale=#{locale}&jsonp=Load.setGem',
                link:'http://#{domaine}/wow/#{locale}/item/#{item}'},
           data:{classes:'http://#{domaine}/api/wow/data/character/classes?locale=#{locale}&jsonp=Load.setClasses',
                 races:'http://#{domaine}/api/wow/data/character/races?locale=#{locale}&jsonp=Load.setRaces',
                 realms:'http://#{domaine}/api/wow/realm/status?jsonp=Load.setRealms',
                 itemsClasses:'http://#{domaine}/api/wow/data/item/classes?jsonp=Load.setItemsClasses'
                }
          },
  regions:{'eu':{domaine:'eu.battle.net',
                 media  :'eu.media.blizzard.com'},
           'us':{domaine:'us.battle.net',
                 media  :'us.media.blizzard.com'},
           'kr':{domaine:'kr.battle.net',
                 media  :'kr.media.blizzard.com'},
           'tw':{domaine:'tw.battle.net',
                 media  :'tw.media.blizzard.com'},
           'cn':{domaine:'www.battlenet.com.cn',
                 media  :'content.battlenet.com.cn'}},
  locales : ['en', 'fr', 'es', 'de', 'ru', 'ko', 'zh'],
  getLocale : function() { return (navigator.language || navigator.browserLanguage).substring(0,2); },
  getUrl : function(pattern, hash) { return new Template(pattern).evaluate(hash); },
  load : function (url, opts) {
  try {
    var opts = opts || {};
    var head = document.getElementsByTagName("head")[0];
    var script = new Element ('script', {"type": "text/javascript", "src": url, "async": true});
    if (opts.callback) {
      script.onreadystatechange = function () { if (this.readyState == 'complete') opts.callback(); }
      script.onload = opts.callback();
    }
    if (opts.error_callback) {
      script.onerror = opts.error_callback;
    }
    head.appendChild(script);
    head.removeChild(script);
  } catch (e) { console.log(e); }
  }
};

Front.Search = {
  enable : function() {
  try {
    $(this).enable();
  } catch (e) { console.log(e); }
  },
  disable : function() {
  try {
    $(this).disable();
  } catch (e) {console.log(e); }
  },
  Character : function(el) {
  try {
    var realm = $F($(el).down('select[name=realms]'));
    var cname = $F($(el).down('input[name=cn]'));
    if (cname.blank()) return false;
    $('searchCharacter').fire('Front:onRefreshStart');
    Data.Character.load({realm:realm, cname:cname});
  } catch (e) {console.log(e); }
  }
};

var Data = {
  Character : {
    status : {},
    list : [],
    slugs : {},
    load : function(opts) {
      if (opts.realm == undefined || opts.cname == undefined) return;
// ToDo : tester si character deja loader
      Data.Character.list.push(new Character(opts));
    }
  },
  Item : {
    status : {},
    list : {},
    slugs : {},
    load : function(opts) {
      if (opts.id == undefined) return;
      if (opts.id in Data.Item.list) {
        if ('locale' in opts && opts.locale in Data.Item.list[opts.id]['locale']) return Data.Item.list[opts.id];
        return Data.Item.list[opts.id] = Data.Item.list[opts.id].call(opts);
      }
      return Data.Item.list[opts.id] = new Item(opts);
    }
  }
};

var Load = {
  status : {init:null, items:{}, gems:{}, characters:{}, classes:null, races:null, realms:null},
//  items : {},
//  gems : {},
//  characters : {},
  data : {classes:{}, races:{}, realms:{}},
/*
  callGem : function(id, opts) {
  try {

    var opts = opts || {key:'id',
                        slug : id + '-en',
                        item:id,
                        locale:'en',
                        domaine:Front.regions[region].domaine
                       };

    if (localStorage[opts.slug]) {
      Load.gems[id] = new Item(localStorage.getObject(opts.slug).data);
      return 2;
    }
    return Load.status.gems[id] = Front.load(Front.getUrl(Front.statics.gem.api, opts));
  } catch (e) { console.log(e); }

  },
*/
  callData : function() {
  try {
    var hash = {locale:Front.getLocale(), domaine:Front.regions[region].domaine};
    Front.load('/lib/enchants.json');
    Front.load('/lib/statname.json');
    Front.load('/lib/suffix.json');
    Load.onInitChange('classes', Front.load(Front.getUrl(Front.statics.data.classes, hash)));
    Load.onInitChange('races', Front.load(Front.getUrl(Front.statics.data.races, hash)));
    Load.onInitChange('realms', Front.load(Front.getUrl(Front.statics.data.realms, hash)));
//    Load.onInitChange('itemsClasses', Front.load(Front.getUrl(Front.statics.data.itemsClasses, hash)));
  } catch (e) { console.log(e); }
  },
  setRegions : function() {
  try {
    var regionsElt = $('searchCharacter').down('select[name=regions]').update('');
    regionsElt.observe('change', function(event) {
      $('searchCharacter').fire('Front:onRefreshStart');
      Front.region = $F(Event.element(event));
      var hash = {locale:Front.getLocale(),
                  domaine:Front.regions[Front.region].domaine};

      Load.onInitChange('realms', Front.load(Front.getUrl(Front.statics.data.realms, hash)));
    } );
    $H(Front.regions).each(function(hash) { regionsElt.appendChild(new Element('option', {value:hash.key}).update(hash.value.domaine)) });
  } catch (e) {console.log(e); }
  },
  setClasses : function(obj) { Load.onInitChange('classes', 1); obj.classes.each(function(el){ Load.data.classes[el.id] = el; }); Load.onInitChange('classes', 2); },
  setRaces   : function(obj) { Load.onInitChange('races', 1);   obj.races.each(function(el){ Load.data.races[el.id] = el; }); Load.onInitChange('races', 2); },
  setRealms  : function(obj) {
  try {
    var realmsElt = $('searchCharacter').down('select[name=realms]').update('');
    Load.onInitChange('realms', 1);
    obj.realms.each(function(el) {
      Load.data.realms[el.slug] = el;
      realmsElt.appendChild(new Element('option', {value:el.name}).update(el.name))
    });
    Load.onInitChange('realms', 2);
    $('searchCharacter').fire('Front:onRefreshEnd');
  } catch (e) { console.log(e); }
  },
//  setItemsClasses  : function(obj) { Load.onInitChange('itemsClasses', 1);  obj.classes.each(function(el){ Load.data.itemsClasses[el.class] = el; }); Load.onInitChange('itemsClasses', 2); },
/*
  setGem : function(obj) {
  try {
    if ($H(Load.gems).keys().indexOf(obj.id) < 0) {
      Load.onGemChange(obj.id, 1);
      Load.gems[obj.id] = new Item(obj);
      if (localStorage in window) localStorage.setObject(obj.id + '-en', Load.gems[obj.id]);
      else ; // todo gerer via cookie...
      Load.onGemChange(obj.id, 2);
    }
  } catch (e) { console.log(e); }
  },
*/
  init : function() {
  try {
    $(document.body).observe('Load:onInitComplete', Load.onInitComplete);
    $('searchCharacter').observe('Front:onRefreshStart', Front.Search.disable);
    $('searchCharacter').observe('Front:onRefreshEnd', Front.Search.enable);
    Load.setRegions();
    Load.callData();
  } catch (e) { console.log(e); }
  },
  onInitComplete : function() {
  try {
    Load.status.init = 1;
//    Load.callCharacter("Throk'Feroth", 'Viciousstab');
//    Load.callCharacter("Throk'Feroth", 'Waynounayheu');
//    Load.callCharacter("Throk'Feroth", 'faerion');
    Data.Character.load({realm:"Throk'Feroth", cname:'faerion'});
  } catch (e) { console.log(e); }
  },
  onInitChange : function(name, status) {
  try {
    Load.status[name] = status;
    if (Load.status.init) return;
    var isFinish = true;
    if (Load.status.classes != 2) isFinish = false;
    if (Load.status.races != 2) isFinish = false;
    if (Load.status.realms != 2) isFinish = false;
    if (isFinish) $(document.body).fire('Load:onInitComplete');
  } catch (e) { console.log(e); }
  }
/*
  onGemChange : function(gem_id, status) {
  try {
    Load.status.gems[gem_id] = status;
  } catch (e) { console.log(e); }
  },
*/
};

var Item = Class.create({
/*
  stats : {},
  icons : {18:null, 56:null},
*/
  initialize: function(opts, hash) {
  try {
    this.id = opts.id;
    this.defaultLocale = Front.getLocale();
    this.locale = {};
    this.hash = hash || {};
    this.hash['item'] = opts.id;
    this.hash['locale'] = this.hash['locale'] ? this.hash['locale'] : this.defaultLocale;
    this.hash['domaine'] = Front.regions[region].domaine;
    this._index = opts.id;
    this.call();
    return this;
  } catch(e) { console.log(e); }
  },
  call : function(hash) {
  try {
    if (hash && 'locale' in hash) this.hash['locale'] = hash.locale;
    var hash = hash || {};
    hash['item'] = this.id;
    hash['locale'] = this.hash['locale'];
    hash['domaine'] = Front.regions[region].domaine;
    hash['jsonp'] = "Data.Item.list[" + this._index + "].set";

    this.hash['locale'] = hash.locale || this.defaultLocale;
    if ('localStorage' in window && localStorage.getObject(this.id) && false) {
      this.set(localStorage.getObject(this.id));
    } else {
      Front.load(Front.getUrl(Front.statics.item.api, hash));
    }
    return this;
  } catch (e) { console.log(e); }
  },
  set : function(obj) {
  try {
    var data = $H(obj).clone();
    if ('localStorage' in window && !localStorage.getObject(this.id)) localStorage.setObject(this.id, data);
    if (!this.locale[this.hash['locale']]) this.locale[this.hash['locale']] = {data:data};
    else this.locale[this.hash['locale']].data = data;
    this.name = data.get('name');
    var bonusStats = data.get('bonusStats');
    var stats = {};
    bonusStats.each(function(bonusStat) {
      var bonusStat = $H(bonusStat);
      if (bonusStat.get('stat') == undefined || bonusStat.get('amount') == undefined) return;
      stats[Load.data.statname[bonusStat.get('stat')]] = bonusStat.get('amount');
    });
    this.stats = stats;
//    delete(bonusStats);

    var icons = {};
    var iconSizes = $A(Front.statics.media.iconSize);
    for (size in iconSizes) {
      if (isNaN(iconSizes[size])) break;
      icons[iconSizes[size]] = new Element('img');
      icons[iconSizes[size]].src = Front.getUrl(Front.statics.media.icon, {size:iconSizes[size], icon:data.get('icon'), domaine:Front.regions[region].media});
    }
    this.locale[this.hash['locale']].icons = icons;

//    delete(icons);

    var hash = {item:data.get('id'),
                locale:this.defaultLocale,
                domaine:Front.regions[region].domaine
               };
    this.link = Front.getUrl(Front.statics.item.link, hash);
    this.onComplete();
//    delete(this.data.bonusStats);
  }catch(e){ console.log(e); }
  },
  onComplete : function() {
    Load.status.items[this.id] = 2;
    if (Data.Item.slugs[this.id]) {
      var that = this;
      $H(Data.Item.slugs[this.id]).each(function (character) {
        var character = character;
        character.value.slots.each(function (slot) {
          Data.Character.list[character.value.index].onItemComplete({id:that.id, slot:slot});
        })
      });
    }
  },
  getDetailsAsElement : function(opts) {
  try {

    var opts = opts || {};
    var container = new Element('div');
//console.log(this.defaultLocale, this.locale, this.locale[this.defaultLocale].icons);
    container.update(new Element('a', {href:this.link}).update(this.locale[this.defaultLocale].icons[18]).insert(opts.name || this.name));
    var statsElt = new Element('div').addClassName('stats');
    container.insert(statsElt);
    var stats = $H(this.stats).clone();
    if (opts.stats) {
      var thisStats = $H(opts.stats).clone();
      thisStats.each(function(thisStat) {
        if (stats.get(thisStat.key)) stats.set(thisStat.key, stats.get(thisStat.key) + parseInt(thisStat.value));
        else stats.set(thisStat.key, parseInt(thisStat.value));
      });
    }
    stats.each(function (stat) {
      if (stat.key == undefined) return;
      statsElt.insert(new Element('div').update((isNaN(stat.key) ? stat.key : Load.data.statname[stat.key]) + ':' + stat.value));
    });
    return container;
  }catch(e){ console.log(e);}
  }
}
);

var Character = Class.create({
  initialize: function(opts) {
  try {
    this.opts = opts;
    this._index = Data.Character.list.length;
    this.slug = (this.opts.realm + '-' + this.opts.cname).toLowerCase().replace(/'/g, '');
    this.call();
    return this;
  } catch(e) { console.log(e); }
  },
  call : function() {
  try {
    var opts = {error_callback : this.errorCall.bind(this), slug:this.slug};
    var hash = {realm:this.opts.realm,
                character:this.opts.cname,
                locale:Front.getLocale(),
                domaine:Front.regions[region].domaine,
                jsonp:"Data.Character.list[" + this._index + "].set"
               };
    Front.load(Front.getUrl(Front.statics.character.api, hash), opts);
  } catch (e) { console.log(e); }
  },
  set : function(obj) {
  try {

    var data = $H(obj).clone();
    this.data = data;
    this.items = $H(data.get('items')).clone();
    this.items.set('status', {});
    this.gems = $H({status : {}});

    var hash = {realm:this.opts.realm,
                character:this.opts.cname,
                locale:Front.getLocale(),
                domaine:Front.regions[region].domaine
               };
    this.link = Front.getUrl(Front.statics.character.link, hash);

    var hash = {avatar:data.get('thumbnail'),
                region:region,
                domaine:Front.regions[region].domaine
               };
    this.avatar = new Image();
    this.avatar.src = Front.getUrl(Front.statics.media.avatar, hash);

    var hash = {race : Load.data.races[data.get('race')].name,
                classe : Load.data.classes[data.get('class')].name,
                guild : (data.get('guild') ? data.get('guild').name : ''),
                level:data.get('level'),
                name:this.opts.cname,
                realm:this.opts.realm
               }
    this.description = new Template('#{name} (#{guild}) #{classe} #{race} lvl#{level}, #{realm}').evaluate(hash);
    Data.Character.slugs[this.slug] = this._index;
    this.loadItems();
  } catch (e) { console.log(e); }
  },
  errorCall : function() {
  try {
//console.log(this, arguments);
//delete(Load.characters[res.slug]);
   alert('Impossible de charger ' + this.opts.realm + ' ' + this.opts.cname);
   $('searchCharacter').fire('Front:onRefreshEnd');
  }catch(e){ console.log(e);}

  },
  onComplete : function(evt) {
  try {
    $('searchCharacter').fire('Front:onRefreshEnd');
    this.getStats();
//    $('searchCharacter').fire('Front:onRefreshEnd');
//    Load.characters[slug].place();
//    alert('character loaded (' + slug + ')' );
    this.place();
  } catch (e) { console.log(e); }
  },
  loadItems : function(el) {
  try {
    if (this.items) {
      $H(this.items).each(this.callItem.bind(this));
    }
  } catch(e){ console.log(e); }
  },
  callItem : function(el) {
  try {
//console.log(this, el);
    var slug = el.key + '-' + el.value.id;
    if (!this.items.get('status')) this.items.set('status', {});
//    if (!this.gems.get('status')) this.gems.set('status', {});
    if (el.value.id && this.items.get('status')[slug] == undefined) {
/*
      var opts = {error_callback : this.errorCall.bind(this), slug:this.slug};
      var hash = {realm:this.opts.realm,
                  character:this.opts.cname,
                  locale:Front.getLocale(),
                  domaine:Front.regions[region].domaine,
                  jsonp:"Data.Character.list[" + this._index + "].set"
                 };
*/
      if (!Data.Item.slugs[el.value.id]) Data.Item.slugs[el.value.id] = {}
      if (!Data.Item.slugs[el.value.id][this.slug]) Data.Item.slugs[el.value.id][this.slug] = {index:this._index, slots:[]};
      Data.Item.slugs[el.value.id][this.slug]['slots'].push(el.key);
      Data.Item.load({id:el.value.id});
      this.items.get('status')[slug] = 0;
/*
      for (var i=0; i < Front.maxGem; i++) {
        if (el.value.tooltipParams['gem'+i] && this.items.get('status')[el.value.tooltipParams['gem'+i]] == undefined) {
          this.items.get('status')[el.value.tooltipParams['gem'+i]] = Load.callItem(el.value.tooltipParams['gem'+i]);
          if (this.gems.get('status')[el.value.id] == undefined) {
            this.gems.get('status')[el.value.tooltipParams['gem'+i]] = Load.callGem(el.value.tooltipParams['gem'+i]);
          }
        }
      }
*/
    }
  } catch(e){ console.log(e); }
  },
  setItem : function(obj) {
  try {
    if ($H(Load.items).keys().indexOf(obj.id) < 0) {
      Load.onItemChange(obj.id, 1);
      Load.items[obj.id] = new Item(obj);
/*
      if (localStorage in window) localStorage.setObject(obj.id + '-' + Front.getLocale(), Load.items[obj.id]);
      else ; // todo gerer via cookie...
*/
      Load.onItemChange(obj.id, 2);
    }
  } catch (e) { console.log(e); }
  },
  onItemChange : function () {
  try {
//    this.items.get('status')[item_slug] = Load.status.items[item_id];
    var itemsStatus = $H(this.items.get('status')).values();
    var itemsStatusLength = itemsStatus.length;// - $H(character.gems.get('status')).values().length;
    if (itemsStatusLength == $H(this.items).values().length-3 && itemsStatus.sum() == (itemsStatusLength*2)) {
      this.onComplete();
    }
  } catch (e) { console.log(e); }
  },
  onItemComplete : function (opts) {
//    console.log(this, opts);
    var slug = opts.slot + '-' + opts.id;
    this.items.get('status')[slug] = 2;
    this.onItemChange();
  },
  getStats : function() {
  try {
    $H(this.items).each((function (slot) {
      var itemSlot = slot.value;
      if (itemSlot.tooltipParams) {
        var seed = itemSlot.tooltipParams.seed;
        var suffix = parseInt(itemSlot.tooltipParams.suffix);
        var reforge = parseInt(itemSlot.tooltipParams.reforge);
//if (suffix < 0) console.log(this.slug, slot.key, Load.data.suffix[suffix * -1].enchant, $H(Load.data.suffix[suffix * -1].enchant).values());

        if (suffix < 0) $H(Load.data.suffix[suffix * -1].enchant).values().each(this.getRandomStats.bind(this, slot.key, seed));
        if (reforge > 0) this.getReforgeStats(slot.key, itemSlot, reforge); //OK
//      if (hasSockets)  this.getGemsStats(slot);
      }
    }).bind(this));

  } catch(e){ console.log(e); }
  },
  getGemsStats : function(slot) {
  try {
    if (this.items.get(slot.key).stats == undefined) this.items.get(slot.key).stats = {};
    var stats = {};
    for (var i=0; i<4; i++) {
      if (slot.value.tooltipParams['gem'+i]) {
        var gemInfo = Load.gems[slot.value.tooltipParams['gem'+i]].data.get('gemInfo').bonus.name.toLowerCase();
        var reg1 = new RegExp('([+-]*\\d+) (.*) and ([+-]*\\d+) (.*)', "ig");
        var reg2 = new RegExp('([+-]*\\d+) (.*) and (.*)', "ig");
        var reg3 = new RegExp('([+-]*\\d+) (.*)', "ig");
/*
console.log(gemInfo);
console.log(gemInfo.replace(, "$1|$2:$3|$4"));
console.log(gemInfo.replace(, "$1|$2:$3"));
console.log(gemInfo.replace(, "$1|$2"));
*/

        if (reg1.test(gemInfo)) {
          var bonusStat = gemInfo.replace(reg1, "$1|$2:$3|$4");
          var bonusStats = bonusStat.split(':');
          for (stat in bonusStats) {
            if (Object.isFunction(bonusStats[stat])) break;
//              stat[vals[1]] += parseInt(vals[0]);
            var vals = bonusStats[stat].split('|');
//console.log(vals[1], parseInt(vals[0]));
            var statName = vals[1].toUpperCase().replace(' ', '_');
            if (this.items.get(slot.key).stats[statName] > 0) {
              this.items.get(slot.key).stats[statName] += parseInt(vals[0]);
            } else {
              this.items.get(slot.key).stats[statName] = parseInt(vals[0]);
            }
          }
        } else if (reg2.test(gemInfo)) {
          var bonusStat = gemInfo.replace(reg2, "$1|$2:$3");
          var bonusStats = bonusStat.split(':');
          for (stat in bonusStats) {
            if (Object.isFunction(bonusStats[stat])) break;
            if (bonusStats[stat].indexOf('|') > -1) {
//              stat[vals[1]] += parseInt(vals[0]);
              var vals = bonusStats[stat].split('|');
//console.log(vals[1], parseInt(vals[0]));
              var statName = vals[1].toUpperCase().replace(' ', '_');
              if (this.items.get(slot.key).stats[statName] > 0) {
                this.items.get(slot.key).stats[statName] += parseInt(vals[0]);
              } else {
                this.items.get(slot.key).stats[statName] = parseInt(vals[0]);
              }
            } else console.log(bonusStats[stat]);
          }
        } else if (reg3.test(gemInfo)) {
//            stat[vals[1]] += parseInt(vals[0]);
          var vals = gemInfo.replace(reg3, "$1|$2").split('|');
//console.log(vals[1], parseInt(vals[0]));
          var statName = vals[1].toUpperCase().replace(' ', '_');
          if (this.items.get(slot.key).stats[statName] > 0) {
            this.items.get(slot.key).stats[statName] += parseInt(vals[0]);
          } else {
            this.items.get(slot.key).stats[statName] = parseInt(vals[0]);
          }
        }
      }
    }
//console.log(this.items.get(slot.key).stats);
  } catch(e){ console.log(e); }
  },
  getRandomStats : function(slot, seed, enchant) {
  try {
    if (this.items.get(slot).stats == undefined) this.items.get(slot).stats = {};
    var statName = Load.data.statname[enchant.name];
    var amount = Math.floor((seed & 65535) * enchant.factor);
    if (this.items.get(slot).stats[statName] > 0)
      this.items.get(slot).stats[statName] += amount;
    else
      this.items.get(slot).stats[statName] = amount;
  } catch(e){ console.log(e); }
  },
  getReforgeStats : function(slot, itemSlot, reforge) {
  try {
    if (Data.Item.list[itemSlot.id]) {
      if (this.items.get(slot).stats == undefined) this.items.get(slot).stats = {};
      var statName = Load.data.statname[Load.data.reforge[reforge].m];
      var statMinus = this.items.get(slot).tooltipParams.suffix < 0 ? this.items.get(slot).stats[statName] : Data.Item.list[itemSlot.id].stats[statName];
      var converse = Math.floor(statMinus * 0.399);
      if (this.items.get(slot).stats[statName] > 0) {
        this.items.get(slot).stats[statName] += converse * -1;
      } else {
        this.items.get(slot).stats[statName] = converse * -1;
      }
      this.items.get(slot).stats[Load.data.statname[Load.data.reforge[reforge].p]] = converse;
    }
  } catch(e){ console.log(e); }
  },
  place: function() {
  try {
    var container = $$('#'+this.slug)[0];
    if (!container) {
      container = new Element('div', {id:this.slug}).addClassName('box');
      $('characters-list').insert(container);
    }
    container.update(new Element('a', {href:this.link}).update(this.avatar).insert(this.description));//.insert(this.toString());
    var slots = container.down('.slots');
    if (!container.down('.slots')) {
      slots = new Element('div').addClassName('slots');
      container.insert(slots);
      for (var i=0; i<Load.data.slots.length; i++ ) {
        slots.insert(new Element('div').addClassName(Load.data.slots[i]));
      }
    }
    for (var i=0; i < Load.data.slots.length; i++ ) {
      slot = Load.data.slots[i];
      slots.down('.' + slot).update(slot+' : <br />');
      if (!this.items.get(slot)) {
        slots.down('.' + slot).insert('N/A');
        continue;
      }
      itemSlot = Data.Item.list[this.items.get(slot).id];
      slots.down('.' + slot).insert(itemSlot.getDetailsAsElement(this.items.get(slot)));
    }
  } catch(e){ console.log(e); }
  }
});

document.observe("dom:loaded", Load.init);